package io.bdmc.modules.sys.controller;

import java.time.LocalDateTime;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.bdmc.common.annotation.SysLogger;
import io.bdmc.common.annotation.SysLogger1;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.Constant.ModifyName;
import io.bdmc.common.validator.Assert;
import io.bdmc.common.validator.ValidatorUtils;
import io.bdmc.common.validator.group.AddGroup;
import io.bdmc.common.validator.group.UpdateGroup;
import io.bdmc.modules.sys.entity.SysUser;
import io.bdmc.modules.sys.service.SysUserService;

/**
 * 系统用户
 * 
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;

	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	public R list(@RequestParam Map<String, String> params) {
		// 查询列表数据
		Long current = Long.valueOf(params.get("current"));
		Long size = Long.valueOf(params.get("size"));
		String username = params.get("username");
		MyPage<SysUser> myPage = new MyPage<SysUser>(current, size);
		MyPage<SysUser> map = sysUserService.queryList(myPage, username);
		return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R info() {
		SysUser u =  getUser();
		return R.ok().put("data",u);
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLogger("修改密码")
	@PostMapping("/password")
	public R password(@RequestBody Map<String, String> params) {
		String password = params.get("password");
		String newPassword = params.get("newPassword");

		Assert.isBlank(newPassword, "新密码不为能空");

		// sha256加密
		password = new Sha256Hash(password, getUser().getSalt()).toHex();

		// sha256加密
		newPassword = new Sha256Hash(newPassword, getUser().getSalt()).toHex();

		// 更新密码
		SysUser user = sysUserService.getById(getUserId());
		if (!user.getPassword().equals(password)) {
			return R.error("原密码不正确");
		}

		user.setPassword(newPassword);
		boolean b = user.updateById();
		return R.trueOrFalse(b);
	}

	/**
	 * 重置用户密码
	 */
	@SysLogger("重置密码")
	@PostMapping("/resetpwd")
	public R resetPwd(@RequestBody Long userId) {
		SysUser user = sysUserService.getById(userId);
		if (user == null)
			return R.error("参数错误。");
		// sha256加密
		String newPassword = new Sha256Hash("123456", user.getSalt()).toHex();
		// 更新密码
		user.setPassword(newPassword);
		boolean count = user.updateById();
		// boolean count = sysUserService.resetPassword(user.getUserId(),newPassword);
		return R.trueOrFalse(count);
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	// @RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId) {
		SysUser user = sysUserService.QueryObject(userId);
		return R.ok().put("data", user);
	}

	/**
	 * 保存用户
	 */
	@PostMapping("/save")
	@SysLogger1(value = "新增用户", entityType = SysUser.class, operationType = ModifyName.ADD)
	// @RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUser user) {
		ValidatorUtils.validateEntity(user, AddGroup.class);
		user.setCreateBy(getUser().getUsername());
		user.setCreateTime(LocalDateTime.now());
		// sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		Boolean r = sysUserService.save(user);

		return R.trueOrFalse(r);
	}

	/**
	 * 修改用户
	 */
	@SysLogger1(value = "修改用户", entityType = SysUser.class, operationType = ModifyName.UPDATE)
	@PostMapping("/update")
	// @RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUser user) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		sysUserService.updateById(user);
		return R.ok();
	}

	/**
	 * 删除用户
	 */
	// @SysLogger("删除用户")
	@SysLogger1(value = "删除用户", entityType = SysUser.class, operationType = ModifyName.DELETE)
	@PostMapping("/delete")
	// @RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long userId) {
		if (userId == 1L) {
			return R.error("系统管理员不能删除");
		}

		if (userId == getUserId()) {
			return R.error("当前用户不能删除");
		}

		sysUserService.removeById(userId);
		return R.ok();
	}

	@SysLogger("设置中心点")
	@PostMapping("/location")
	public R updateCenterLocation(@RequestBody String centerLocation) {
		SysUser u = getUser();
		u.setCenterLocation(centerLocation);
		u.updateById();
		return R.ok();
	}
}
